package com.serkol.ams.security.handler;

import cn.hutool.core.bean.BeanUtil;

import com.alibaba.fastjson2.JSON;
import com.serkol.ams.module.sys.entity.SysUsers;
import com.serkol.ams.utils.JwtUtils;
import com.serkol.ams.utils.LoginResult;
import com.serkol.ams.utils.RedisUtil;
import com.serkol.ams.vo.ReturnCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;


/**
 * 登录认证成功处理类
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //设置响应的编码格式
        response.setContentType("application/json;charset=UTF-8");
        //获取当前登录用户的信息
        SysUsers user = (SysUsers) authentication.getPrincipal();
       // UserLoginVo userLoginVo = new UserLoginVo();
       // BeanUtil.copyProperties(user, userLoginVo);
        //生成token
        String token = jwtUtils.getJwtToken(user.getId()+"",user.getUsername());
        //将token信息保存到Redis中
        String tokenKey = "token_"+token;
        redisUtil.set(tokenKey, token,18000);
        //LoginResult登录结果对象
        LoginResult loginResult = new LoginResult(user.getId(), ReturnCodeEnum.RC200.getCode(),user,token,redisUtil.getExpire("token_"+token));
        //将对象转换成json
        String result = JSON.toJSONString(loginResult);
        //获取输出流
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(result.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();

    }
}
